<?php
//рус
include_once (_CORE_PATH . "request/request_prototype.php");
class request_http extends request_prototype_class
{
    /**
     * REQUEST_URI
     * @var string;
     */
    private $_requestUri;
    private $_basePath;
    /**
     * Constructor
     *
     * If a $uri is passed, the object will attempt to populate itself using
     * that information.
     *
     * @param string|Zend_Uri $uri
     * @return void
     * @throws Zend_Controller_Request_Exception when invalid URI passed
     */
    public function __construct ()
    {
		$this->NoMagicQuotesGPC($_GET);
		$this->NoMagicQuotesGPC($_POST);
		$this->NoMagicQuotesGPC($_COOKIE);        
        
        $this->setRequestUri();
    }
    
	public function NoMagicQuotesGPC(&$var)
	{
		if (!get_magic_quotes_gpc()) return;
		if (is_string($var))
		{
			$var = stripslashes($var);
		}
		elseif (is_array($var))
		{
			foreach($var AS $key => $value)
			{
				$this->NoMagicQuotesGPC($var[$key]);
			}
		}
		elseif (is_object($var))
		{
			foreach(get_object_vars($var) AS $key => $value)
			{
				$this->NoMagicQuotesGPC($var->$key);
			}
		}
	}    
    /**
     * Access values contained in the superglobals as public members
     * Order of precedence: 1. GET, 2. POST, 3. COOKIE, 4. SERVER, 5. ENV
     *
     * @see http://msdn.microsoft.com/en-us/library/system.web.httprequest.item.aspx
     * @param string $key
     * @return mixed
     */
    public function __get ($key)
    {
        switch (true) {
            case isset($_GET[$key]):
                return $_GET[$key];
            case isset($_POST[$key]):
                return $_POST[$key];
            case isset($_FILES[$key]):
                return $_FILES[$key];
            case isset($_COOKIE[$key]):
                return $_COOKIE[$key];
            case ($key == 'REQUEST_URI'):
                return $this->getRequestUri();
            case isset($_SERVER[$key]):
                return $_SERVER[$key];
            case isset($_ENV[$key]):
                return $_ENV[$key];
            default:
                return null;
        }
    }
    /**
     * Alias to __get
     *
     * @param string $key
     * @return mixed
     */
    public function get ($key)
    {
        return $this->__get($key);
    }
    /**
     * Set values
     *
     * In order to follow {@link __get()}, which operates on a number of
     * superglobals, setting values through overloading is not allowed and will
     * raise an exception. Use setParam() instead.
     *
     * @param string $key
     * @param mixed $value
     * @return void
     * @throws Zend_Controller_Request_Exception
     */
    public function __set ($key, $value)
    {}
    /**
     * Alias to __set()
     *
     * @param string $key
     * @param mixed $value
     * @return void
     */
    public function set ($key, $value)
    {
        return $this->__set($key, $value);
    }
    /**
     * Check to see if a property is set
     *
     * @param string $key
     * @return boolean
     */
    public function __isset ($key)
    {
        switch (true) {
            case isset($_GET[$key]):
                return true;
            case isset($_POST[$key]):
                return true;
            case isset($_FILES[$key]):
                return true;
            case isset($_COOKIE[$key]):
                return true;
            case isset($_SERVER[$key]):
                return true;
            case isset($_ENV[$key]):
                return true;
            default:
                return false;
        }
    }
    /**
     * Alias to ____isset
     *
     * @param string $key
     * @return mixed
     */
    public function has ($key)
    {
        return $this->__isset($key);
    }
    /**
     * Retrieve a member of the $_GET superglobal
     *
     * If no $key is passed, returns the entire $_GET array.
     *
     * @todo How to retrieve from nested arrays
     * @param string $key
     * @param mixed $default Default value to use if key not found
     * @return mixed Returns null if key does not exist
     */
    public function getQuery ($key = null, $default = null)
    {
        if (null === $key) {
            return $_GET;
        }
        return (isset($_GET[$key])) ? $_GET[$key] : $default;
    }
    
    public function hasQuery($key)
    {
    	return isset($_GET[$key]);
    }
    /**
     * Retrieve a member of the $_POST superglobal
     *
     * If no $key is passed, returns the entire $_POST array.
     *
     * @todo How to retrieve from nested arrays
     * @param string $key
     * @param mixed $default Default value to use if key not found
     * @return mixed Returns null if key does not exist
     */
    public function getPost ($key = null, $default = null)
    {
        if (null === $key) {
            return $_POST;
        }
        return (isset($_POST[$key])) ? $_POST[$key] : $default;
    }
    
    public function PostToInputs($data = false, $pKey = '')
    {
    	if (false === $data) $data = $this->getPost();

    	$inputs = '';
    	foreach ($data as $key=>$value)
    	{
    		if ($pKey) $key = $pKey. '[' .htmlspecialchars($key). ']';
    		
    		if (is_array($value)) 
    		{
    			$inputs .= $this->PostToInputs($value, $key);
    			continue;
    		}
    	
    		$inputs .= '<input type="hidden" name="' .$key. '" value="' .htmlspecialchars($value). '">';
    	}
    	
    	return $inputs;
    }
    
    public function getFile ($key = null, $default = null)
    {
        if (null === $key) {
            return $_FILES;
        }
        return (isset($_FILES[$key])) ? $_FILES[$key] : $default;
    }
    /**
     * Retrieve a member of the $_COOKIE superglobal
     *
     * If no $key is passed, returns the entire $_COOKIE array.
     *
     * @todo How to retrieve from nested arrays
     * @param string $key
     * @param mixed $default Default value to use if key not found
     * @return mixed Returns null if key does not exist
     */
    public function getCookie ($key = null, $default = null)
    {
        if (null === $key) {
            return $_COOKIE;
        }
        return (isset($_COOKIE[$key])) ? $_COOKIE[$key] : $default;
    }
    /**
     * Retrieve a member of the $_SERVER superglobal
     *
     * If no $key is passed, returns the entire $_COOKIE array.
     *
     * @param string $key
     * @param mixed $default Default value to use if key not found
     * @return mixed Returns null if key does not exist
     */
    public function getServer ($key = null, $default = null)
    {
        if (null === $key) {
            return $_SERVER;
        }
        return (isset($_SERVER[$key])) ? $_SERVER[$key] : $default;
    }
    /**
     * Retrieve a member of the $_ENV superglobal
     *
     * If no $key is passed, returns the entire $_COOKIE array.
     *
     * @param string $key
     * @param mixed $default Default value to use if key not found
     * @return mixed Returns null if key does not exist
     */
    public function getEnv ($key = null, $default = null)
    {
        if (null === $key) {
            return $_ENV;
        }
        return (isset($_ENV[$key])) ? $_ENV[$key] : $default;
    }
    /**
     * Set the REQUEST_URI on which the instance operates
     *
     * If no request URI is passed, uses the value in $_SERVER['REQUEST_URI'],
     * $_SERVER['HTTP_X_REWRITE_URL'], or $_SERVER['ORIG_PATH_INFO'] + $_SERVER['QUERY_STRING'].
     *
     * @param string $requestUri
     * @return Zend_Controller_Request_Http
     */
    public function setRequestUri ($requestUri = null)
    {
        if ($requestUri === null) {
            if (isset($_SERVER['HTTP_X_REWRITE_URL'])) { // check this first so IIS will catch
                $requestUri = $_SERVER['HTTP_X_REWRITE_URL'];
            } elseif (isset($_SERVER['REQUEST_URI'])) {
                $requestUri = $_SERVER['REQUEST_URI'];
            } elseif (isset($_SERVER['ORIG_PATH_INFO'])) { // IIS 5.0, PHP as CGI
                $requestUri = $_SERVER['ORIG_PATH_INFO'];
                if (! empty($_SERVER['QUERY_STRING'])) {
                    $requestUri .= '?' . $_SERVER['QUERY_STRING'];
                }
            } else {
                return $this;
            }
        } elseif (! is_string($requestUri)) {
            return $this;
        } else {
            // Set GET items, if available
            $_GET = array();
            if (false !== ($pos = strpos($requestUri, '?'))) {
                // Get key => value pairs and set $_GET
                $query = substr($requestUri, $pos + 1);
                parse_str($query, $vars);
                $_GET = $vars;
            }
        }
        
		if (0 === strpos($requestUri, _ROOT_URL))
        {
        	$requestUri = substr($requestUri, strlen(_ROOT_URL));
        }         
        
        $this->_requestUri = urldecode($requestUri);
        return $this;
    }
    /**
     * Returns the REQUEST_URI taking into account
     * platform differences between Apache and IIS
     *
     * @return string
     */
    public function getRequestUri()
    {
        if (empty($this->_requestUri)) {
            $this->setRequestUri();
        }
        return $this->_requestUri;
    }
    /**
     * Return the method by which the request was made
     *
     * @return string
     */
    public function getMethod ()
    {
        return $this->getServer('REQUEST_METHOD');
    }
    /**
     * Was the request made by POST?
     *
     * @return boolean
     */
    public function isPost ()
    {
        if ('POST' == $this->getMethod()) {
            return true;
        }
        return false;
    }
    /**
     * Return the value of the given HTTP header. Pass the header name as the
     * plain, HTTP-specified header name. Ex.: Ask for 'Accept' to get the
     * Accept header, 'Accept-Encoding' to get the Accept-Encoding header.
     *
     * @param string HTTP header name
     * @return string|false HTTP header value, or false if not found
     * @throws Zend_Controller_Request_Exception
     */
    public function getHeader ($header)
    {
        if (empty($header))
            return false;
            // Try to get it from the $_SERVER array first
        $temp = 'HTTP_' . strtoupper(str_replace('-', '_', $header));
        if (! empty($_SERVER[$temp])) {
            return $_SERVER[$temp];
        }
        // This seems to be the only way to get the Authorization header on
        // Apache
        if (function_exists('apache_request_headers')) {
            $headers = apache_request_headers();
            if (! empty($headers[$header])) {
                return $headers[$header];
            }
        }
        return false;
    }
    /**
     * Is the request a Javascript XMLHttpRequest?
     *
     * Should work with Prototype/Script.aculo.us, possibly others.
     *
     * @return boolean
     */
    public function isXmlHttpRequest ()
    {
        return ($this->getHeader('X_REQUESTED_WITH') == 'XMLHttpRequest');
    }
    
    public function SetCookie($name, $value = null, $expire = null, $path = null, $domain = null, $secure = null, $httponly = null)
    {
    	$_COOKIE[$name] = $value;
    	return setcookie($name, $value, $expire, $path, $domain, $secure, $httponly);
    }
    
    public function GetBasePath ()
    {
        return $this->_basePath;
    }
    public function SetBasePath ($basePath)
    {
        $this->_basePath = $basePath;
    }
}
